home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 3_11.lha / 3_11 / 3_11e.c < prev    next >
C/C++ Source or Header  |  1993-08-08  |  1KB  |  54 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. / convert an integer into a string of max length len
  6. / version 2
  7. include <limits.h>
  8. include <swap.h>
  9. include <error.h>
  10.  
  11. include "3_11e1.c"    /* EXPAND defines TWOSCOMPLEMENT */
  12. include "3_11e2.c"    /* EXPAND defines BITS() */
  13. include "3_11e3.c"    /* EXPAND defines HIBIT() */
  14.  
  15. oid itoa(char *s, int len, int val)
  16.  
  17.    char *p;
  18.    // reverse the sign of negative numbers
  19.    if (val < 0)
  20. {
  21. if (--len <= 0)
  22.     error("string not long enough");
  23. *s++ = '-';
  24. p = s;
  25.  
  26. if (TWOSCOMPLEMENT && (val == INT_MIN))
  27.     {
  28.     if (--len <= 0)
  29.     error("string not long enough");
  30.  
  31. include "3_11e4.c"    /* EXPAND12 divides by 10 */
  32.     }
  33.  
  34. else
  35.     val = -val;
  36. }
  37.  
  38.    else
  39. p = s;
  40.  
  41.    // store digits in reverse order
  42.    do  {
  43. if (--len <= 0)
  44.     error("string not long enough");
  45. *p++ = val % 10 + '0';
  46. val /= 10;
  47.    } while (val != 0);
  48.  
  49.    *p-- = '\0';
  50.    // swap the digits around
  51.    while (s < p)
  52. swap(*s++, *p--);
  53.  
  54.